import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';

// 将s字符串转换为Uint8Array
const s2ab = (s) => {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

// data格式 [[表头[a],表头[b],表头[c]],[数据[a],数据[b],数据[c]],[数据[a],数据[b],数据[c]]]
export const exportExcel = (data, sheetName, fileName) => {
  if(data.length === 1){
    ElMessage.warning('暂无可导出数据');
    // 没有数据不执行导出
    return ;
  }
  // 创建空的workbook对象
  const workbook = XLSX.utils.book_new();
  // 创建新的worksheet对象
  const worksheet = XLSX.utils.aoa_to_sheet(data);
  // 将wroksheet添加到wrokbook中
  XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
  // 生成Excel文件的Binary字符串
  const excelBinaryString = XLSX.write(workbook, { type: 'binary' });
  // 将Binary字符串转换为Blob对象
  const blob = new Blob([s2ab(excelBinaryString)], { type: 'application/octet-stream' });
  // XLSX.writeFileAsync(workbook, fileName);
  // XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });

  if (navigator.msSaveBlob) {
    // 兼容IE浏览器
    navigator.msSaveBlob(blob, fileName);
  } else {
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
  }
  ElMessage.success('导出完成');
}



